package xl.com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xl.com.mapper.OrderItemMapper;
import xl.com.model.OrderItem;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 步骤2：扩展业务数据服务
@Service
@RequiredArgsConstructor
public class BusinessDataService {
    @Autowired
    private final OrderItemMapper orderItemMapper;

    // 订单查询函数
//    @Cacheable(value = "orders", key = "#queryParams.toString()")
    public String queryOrderData(Map<String, String> queryParams) {
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();

        // 安全过滤查询参数
        if (queryParams.containsKey("orderNo")) {
            wrapper.eq("order_no", queryParams.get("orderNo"));
        }
        if (queryParams.containsKey("buyerId")) {
            wrapper.eq("buyer_id", queryParams.get("buyerId"));
        }
        // 其他条件...

        List<OrderItem> orders = orderItemMapper.selectList(queryParams.get("orderNo"));
        return formatOrderResults(orders);
    }

    private String formatOrderResults(List<OrderItem> orders) {
        // 转换为自然语言描述
        return orders.stream()
                .map(order -> String.format("""
                订单号：%s
                状态：%s
                商品：%s x%d
                售后状态：%s
                最后更新时间：%s
                """, order.getOrderNo(), getStatusText(order.getStatus()),
                        order.getProductName(), order.getNum(),
                        getAfsStatusText(order.getAfsStatus()),
                        order.getUpdateTime()))
                .collect(Collectors.joining("\n"));
    }

    private Object getStatusText(Object status) {
        return "已发货";
    }

    // 状态码映射
    private String getAfsStatusText(Integer code) {
        return switch(code) {
            case 0 -> "正常";
            case 10 -> "退款申请中";
            case 20 -> "退款已同意";
            // 其他状态映射...
            default -> "未知状态";
        };
    }

    public String queryOrderData(String query, Integer limit) {
        List<OrderItem> orders = orderItemMapper.selectList(query);
        return formatOrderResults(orders);
    }

//    public String queryOrderData(String query, Integer limit) {
//    }
}